package com.example.springboot3.util;

import com.example.springboot3.config.MyLocaleResolve;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.Locale;

/**
 * @author 张琪
 * @date 2024-02-21 16:19
 */
@Slf4j
@Component
public class I18nUtil {
    @Value("${spring.messages.basename}")
    private String baseName;

    private final MyLocaleResolve resolve;

    private static MyLocaleResolve customLocaleResolver;

    private static String path;

    public I18nUtil(MyLocaleResolve resolve) {
        this.resolve = resolve;
    }

    @PostConstruct
    public void init() {
        setBaseName(baseName);
        setCustomLocaleResolver(resolve);
    }

    public static String getMessage(String code) {
        Locale locale = customLocaleResolver.getLocale();
        return getMessage(code, null, code, locale);
    }

    public static String getMessage(String code, String lang) {

        Locale locale;
        if (StringUtils.isBlank(lang)) {
            locale = Locale.US;
        } else {
            String[] s = lang.split("-");
            locale = new Locale(s[0], s[1]);
        }
        return getMessage(code, null, code, locale);
    }

    public static String getStationLetterMessage(String code, String lang) {
        Locale locale = StringUtils.equals(lang, "zh-CN") ? Locale.SIMPLIFIED_CHINESE : Locale.US;
        return getMessage(code, null, code, locale);
    }

    private static String getMessage(String code, Object[] args, String defaultMessage, Locale locale) {
        ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
        messageSource.setDefaultEncoding(StandardCharsets.UTF_8.toString());
        messageSource.setBasename(path);
        String content;
        try {
            content = messageSource.getMessage(code, args, locale);
        } catch (Exception e) {
            log.error("获取国际化参数失败", e);
            content = defaultMessage;
        }
        return content;
    }

    private void setCustomLocaleResolver(MyLocaleResolve resolve) {
        customLocaleResolver = resolve;
    }

    private void setBaseName(String baseName) {
        path = baseName;
    }
}
